import openpyxl
from flask import jsonify
from dao.nurse import psychological_list_dao
import json

def list_read():
    result = psychological_list_dao.read()

    if result:
        user_first = result
        print(user_first)
        result = {"code": 20000, "err": 0, "message": "查看患者列表成功",
                  "data": {"userinfo": user_first}}
    else:
        result = {"err": 2, "message": "无数据", "data": {}}
    return result

def id_delete(data):
    id = data["id"]
    print(id)
    result = psychological_list_dao.id_delete(id)

    if result:
        user_first = result
        print(user_first)
        result = {"code": 20000, "err": 0, "message": "删除成功",
                  "data": {"userinfo": user_first}}
    else:
        result = {"err": 2, "message": "删除失败", "data": {}}
    return result

def add(data):
    print("原来的data", data)
    # 提取qlq_score并转换为JSON格式的字符串
    qlq_score_str = json.dumps(data['qlq_score'])
    data['qlq_score'] = f'{qlq_score_str}'
    print("修改后的data", data)

    result = psychological_list_dao.add(data)

    if result:
        user_first = result
        print(user_first)
        result = {"code": 20000, "err": 0, "message": "新增成功",
                  "data": {"userinfo": user_first}}
    else:
        result = {"err": 2, "message": "新增失败", "data": {}}
    return result

def update(data):

    # 提取qlq_score并转换为JSON格式的字符串
    qlq_score_str = json.dumps(data['qlq_score'])
    data['qlq_score'] = f'{qlq_score_str}'

    id = data.pop('id', None)

    print(f'打印{data}')

    result = psychological_list_dao.update(data, id)

    if result:
        user_first = result
        print(user_first)
        result = {"code": 20000, "err": 0, "message": "修改成功",
                  "data": {"userinfo": user_first}}
    else:
        result = {"err": 2, "message": "修改失败", "data": {}}
    return result

def num_info(data):
    user_id = data["user_id"]

    result = psychological_list_dao.num_info(user_id)

    if result:
        user_first = result
        print(user_first)
        result = {"code": 20000, "err": 0, "message": f"查看心理量表{user_id}的信息成功",
                  "data": {"userinfo": user_first}}
    else:
        result = {"err": 2, "message": "查询结果为空", "data": {}}
    return result

def importing(file):

    # 如果用户没有选择文件，浏览器也可能提交一个没有文件名的空部分
    # 所以我们需要检查文件是否为空
    if file.filename == '':
        return jsonify({"error": "No selected file"}), 400

    if file:
        try:
            # 使用 openpyxl 加载 Excel 文件
            workbook = openpyxl.load_workbook(filename=file, read_only=True)
            sheet = workbook.active  # 获取活动的工作表

            # 读取并返回第一个工作表的所有行
            rows = []

            for row in sheet.iter_rows(values_only=True):
                rows.append(list(row))

            datas = [
                {header: value for header, value in zip(rows[0], row)}  # 使用标题行作为字典的键
                for row in rows[1:]  # 从第二行开始迭代
            ]

            result = psychological_list_dao.importing(datas)

            if result >= 1:
                info = result
                print(info)
                result = {"code": 20000, "err": 0, "message": "导入成功",
                          "data": {"userinfo": info}}
            else:
                result = {"err": 2, "message": "导入失败", "data": {}}
            return result
        except Exception as e:
            return jsonify({"error": str(e)}), 500

if __name__ == '__main__':
    # import json

    data = {
        'user_id': 2,
        'pss_score': '20',
        'gad_score': 'fvegve',
        'pswq_score': 'sdv',
        'phq_score': 'scfasf',
        'rrs_score': 'brebvsd',
        'prmq_score': 'csdvv',
        'qlq_score': {'domain_scores': {'pain': 2}},
        'psqi_score': 'sdvf',
        'create_time': '2024-09-07 01:29:52',
        'num': 1
    }

    # 提取qlq_score并转换为JSON格式的字符串
    qlq_score_str = json.dumps(data['qlq_score'])

    # 输出结果
    print(f"'{qlq_score_str}'")  # 注意：这里的外层单引号是为了满足您的要求，实际上JSON字符串已经包含了必要的引号
